/**
 * Copyright (c)  HeiFeiDeFengZheng.Co.Ltd. All rights reserved.
 **/
package com.defu.newmall.controller;

import com.defu.newmall.annotation.TokenToUser;
import com.defu.newmall.common.Constants;
import com.defu.newmall.common.Result;
import com.defu.newmall.common.ResultGenerator;
import com.defu.newmall.entity.AdminLoginParam;
import com.defu.newmall.entity.AdminUser;
import com.defu.newmall.entity.AdminUserToken;
import com.defu.newmall.service.AdminUserService;
import com.defu.newmall.vo.UpdateAdminNameParam;
import com.defu.newmall.vo.UpdateAdminPasswordParam;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;

/**
 * 功能描述：
 *
 * @author huifeidefengzheng
 * @since 2024-01-28
 **/
@RestController
@Api(value = "v1", tags = "后台管理系统管理员模块接口")
@Validated
@RequestMapping("/manage-api/v1")
public class NewBeeAdminManageUserController {

    private static final Logger logger = LoggerFactory.getLogger(NewBeeAdminManageUserController.class);

    @Autowired
    private AdminUserService adminUserService;

    @RequestMapping(value = "/adminUser/login", method = RequestMethod.POST)
    public Result<String> login(@Valid @RequestBody AdminLoginParam adminLoginParam, HttpServletResponse response) {
        if (adminLoginParam == null || StringUtils.isEmpty(adminLoginParam.getUserName()) || StringUtils.isEmpty(adminLoginParam.getPasswordMd5())) {
            return ResultGenerator.genFailResult("用户名或密码不能为空");
        }


        AdminUserToken loginResult = adminUserService.login(adminLoginParam.getUserName(), adminLoginParam.getPasswordMd5());
        String token = loginResult.getToken();
        logger.info("manage login api,adminName={},loginResult={}", adminLoginParam.getUserName(), loginResult);

        //登录成功
        if (!StringUtils.isEmpty(loginResult) && token.length() == Constants.TOKEN_LENGTH) {
            Result result = ResultGenerator.genSuccessResult();
            response.setHeader("NewbeeToken",token);
            result.setData(loginResult);
            return result;
        }
        //登录失败
        return ResultGenerator.genFailResult("fail");
    }


    @GetMapping(value = "/test1")
    @ApiOperation(value = "测试接口", notes = "方法中含有@TokenToAdminUser注解")
    public Result<String> test1(@TokenToUser AdminUserToken userToken) {
        //此接口含有@TokenToAdminUser注解，即需要登陆验证的接口。
        Result result = null;
        if (userToken == null) {
            //如果通过请求header中的token未查询到用户的话即token无效，登陆验证失败，返回未登录错误码。
            result = ResultGenerator.genErrorResult(419, "未登录！");
            return result;
        } else {
            //登陆验证通过。
            result = ResultGenerator.genSuccessResult("登陆验证通过");
        }
        return result;
    }

    /**
     * 获取管理员信息接口 根据管理员 id 查询完整的管理员数据，处理完数据并返回管理员信息
     * @param adminUserId
     * @return
     */
    @RequestMapping(value = "/adminUser/profile", method = RequestMethod.GET)
    public Result profile(@NotNull(message = "adminUserId不能为空") Long adminUserId) {
        logger.info("adminUserId:{}", adminUserId);
        AdminUser adminUser = adminUserService.getUserDetailById(adminUserId);
        if (adminUser != null) {
            adminUser.setLoginPassword("******");
            Result result = ResultGenerator.genSuccessResult();
            result.setData(adminUser);
            return result;
        }
        return ResultGenerator.genFailResult("未查询到记录！");
    }

    @RequestMapping(value = "/adminUser/password", method = RequestMethod.PUT)
    public Result passwordUpdate(@Valid @RequestBody UpdateAdminPasswordParam adminPasswordParam){
        logger.info("adminUser:{}", adminPasswordParam.toString());
        if (adminUserService.updatePassword(adminPasswordParam)) {
            return ResultGenerator.genSuccessResult();
        } else {
            return ResultGenerator.genFailResult("未查询到记录！");
        }
    }


    /**
     * 修改管理员信息接口
     */

    @RequestMapping(value = "/adminUser/name", method = RequestMethod.PUT)
    public Result nameUpate(@Valid @RequestBody UpdateAdminNameParam adminNameParam) {
        logger.info("adminNameParam:{}", adminNameParam.toString());
        if (StringUtils.isEmpty(adminNameParam.getLoginUserName()) || StringUtils.isEmpty(adminNameParam.getNickName())) {
            return ResultGenerator.genFailResult("参数不能为空");
        }
        if (adminUserService.updateName(adminNameParam)) {
            return ResultGenerator.genSuccessResult();
        } else {
            return ResultGenerator.genFailResult("插入数据库失败");
        }
    }

    @RequestMapping(value = "/logout", method = RequestMethod.DELETE)
    public Result logout(AdminUserToken adminUser) {
        logger.info("adminUser:{}", adminUser.toString());
        adminUserService.logout(adminUser.getAdminUserId());
        return ResultGenerator.genSuccessResult();
    }
}
